
#include <iostream>
#include <fstream>

#include "servconf.h"
#include "stringutil.h"

namespace tnet
{
	#define valuechar "="
	#define commentchar '#'

	#define defaultIpaddr          "0.0.0.0"
	#define defaultPort            12345
	#define defaultProcess         1
	#define defaultWorkerConntions 1024 
	#define defaultTimeout         60

	ServConf::ServConf()
		: m_ipaddr(defaultIpaddr)
		, m_port(defaultPort)
		, m_maxProcess(defaultProcess)
		, m_worker_connections(defaultWorkerConntions)
		, m_maxIdleTimeout(defaultTimeout)
		, m_length(0)
		, m_reuseport(false)
		, m_unsock(false)
	{
		
	}

	ServConf::~ServConf(){};

	int ServConf::loadConf(const string& conf)
	{
		char buf[1024] = {0};
		std::vector<string> rows;

		m_config = conf;
		std::ifstream fs(m_config.c_str());
		if(!fs.is_open())
		{
			return -1;
		}

		while(!fs.eof())
		{
			memset(buf,0x00,sizeof(buf));
			fs.getline(buf,sizeof(buf)-1);

			string data = StringUtil::strip(buf);
			if(data.empty() || data[0] == commentchar )
			{
				continue;
			}	

			int pos =  data.find_first_of(commentchar);
			if( pos != string::npos )
			{
				data = data.substr(0,pos);
			}

			rows = StringUtil::split(data, valuechar, 2);
			readValue(rows);
			rows.clear();			
		}
		fs.close();
		return 0;
	}

	int ServConf::readValue(vector<string>& rows)
	{
		if(rows.size() == 2)
		{
			if(rows[0].compare("IPADDR") == 0)
				m_ipaddr = rows[1];  
			else if( rows[0].compare("PORT") == 0)
				m_port = atoi(rows[1].c_str());
			else if( rows[0].compare("MAXPROCESS") == 0)
				m_maxProcess = atoi(rows[1].c_str());
			else if( rows[0].compare("WORKERCONNECTIONS") == 0)
				m_worker_connections =  atoi(rows[1].c_str());
			else if( rows[0].compare("MAXIDLETIMEOUT") == 0)
				m_maxIdleTimeout =  atoi(rows[1].c_str());
			else if( rows[0].compare("HEAD_LENGTH") == 0)
				m_length =  atoi(rows[1].c_str());		
			else if( rows[0].compare("REUSEPORT") == 0)
				m_reuseport =  atoi(rows[1].c_str()) ? true : false;			
			else if( rows[0].compare("UNSOCK") == 0)
				m_unsock =  atoi(rows[1].c_str()) ? true : false;		
			else if(rows[0].compare("UNPATH") == 0)
				m_unpath = rows[1];  											
		}
		return 0;
	}
}


